package com.etrans.web.gps.util.message;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.velocity.app.VelocityEngine;
import org.springframework.ui.velocity.VelocityEngineUtils;

import com.etrans.web.gps.util.DateUtil;

/**
 * 邮件发送工具类
 * @author jw.chen
 *
 */
public class MailSendUtil {
    private final static String host = "smtp.163.com"; //163的服务器
    private final static String formName = "realcyi@163.com";//你的邮箱
    private final static String password = "ct20090509"; //授权码
    private final static String replayAddress = "realcyi@163.com"; //你的邮箱
    private static  VelocityEngine velocityEngine = null;
    private static  Map<String, Object> proMap = null;

    /**
     * 发送html格式文本
     * @param info		邮件对象实体类
     * @param model		模块里面用到的参数赋值
     * @throws Exception
     */
    public static boolean sendHtmlMail(MailInfo info,Map<String,Object> model)throws Exception{
        try {
			info.setHost(host);
			info.setFormName(formName);
			info.setFormPassword(password);   //网易邮箱的授权码~不一定是密码
			info.setReplayAddress(replayAddress);

			Message message = getMessage(info);
			// MiniMultipart类是一个容器类，包含MimeBodyPart类型的对象
			Multipart mainPart = new MimeMultipart();
			// 创建一个包含HTML内容的MimeBodyPart
			BodyPart html = new MimeBodyPart();
			// 设置HTML内容
			String text = VelocityEngineUtils.mergeTemplateIntoString(MailSendUtil.getVelocityEngineInstance(), info.getFileName(), "UTF-8", model);
			html.setContent(text, "text/html; charset=utf-8");
			mainPart.addBodyPart(html);
			// 将MiniMultipart对象设置为邮件内容
			message.setContent(mainPart);
			Transport.send(message);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
       return false;
    }

    public static void sendTextMail(MailInfo info) throws Exception {

        info.setHost(host);
        info.setFormName(formName);
        info.setFormPassword(password);   //网易邮箱的授权码~不一定是密码
        info.setReplayAddress(replayAddress);
        Message message = getMessage(info);
        //消息发送的内容
        message.setText(info.getContent());

        Transport.send(message);
    }
    
    public static  VelocityEngine getVelocityEngineInstance() {
        proMap = new HashMap<String, Object>();
        proMap.put("resource.loader", "class");
        proMap.put("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        
        if (null == velocityEngine) {
            synchronized (VelocityEngine.class) {
                if (null == velocityEngine) {
                    velocityEngine = new VelocityEngine();
                    for (Map.Entry<String, Object> entry : proMap.entrySet()) {
                        velocityEngine.setProperty(entry.getKey(), entry.getValue());
                    }
                }
            }
        }
        return velocityEngine;
    }

    private static Message getMessage(MailInfo info) throws Exception{
        final Properties p = System.getProperties() ;
        p.setProperty("mail.smtp.host", info.getHost());
        p.setProperty("mail.smtp.auth", "true");
        p.setProperty("mail.smtp.user", info.getFormName());
        p.setProperty("mail.smtp.pass", info.getFormPassword());

        // 根据邮件会话属性和密码验证器构造一个发送邮件的session
        Session session = Session.getInstance(p, new Authenticator(){
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(p.getProperty("mail.smtp.user"),p.getProperty("mail.smtp.pass"));
            }
        });
        session.setDebug(true);
        Message message = new MimeMessage(session);
        //消息发送的主题
        message.setSubject(info.getSubject());
        //接受消息的人
        message.setReplyTo(InternetAddress.parse(info.getReplayAddress()));
        //消息的发送者
        message.setFrom(new InternetAddress(p.getProperty("mail.smtp.user"),"第三方监管平台"));
        // 创建邮件的接收者地址，并设置到邮件消息中
        message.setRecipient(Message.RecipientType.TO,new InternetAddress(info.getToAddress()));
        // 消息发送的时间
        message.setSentDate(new Date());

        return message ;
    }
    
    public static void main(String[] args) {
    	try {
	    	String mail = "1060205983@qq.com"; //发送对象的邮箱
	        String title = "我有一句话跟你说";
	        MailInfo info = new MailInfo();
	        info.setToAddress(mail);
	        info.setSubject(title);
	        
	        //发送html格式
	        info.setFileName("enterpriseTemplate.html");
	        Map<String,Object> model = new HashMap<String,Object>();
	        //List<AbnomalVeVO> abnomalList =new ArrayList<>();
	        //List<EnterpriseSwap> entList =new ArrayList<>();
	        String entStr ="";
	        for(int i=0;i<10;i++){
	        	entStr += "<tr>"
						+"<td></td>"
						+"<td></td>"
						+"<td></td>"
						+"<td></td>"
						+"<td></td>"
						+"<td></td>"
						+"<td></td>"
						+"<td></td>"
						+"<td></td>"
						+"<td></td>"
						+"</tr>";
	        }
	        String abnomalStr="";
	        for(int i=0;i<10;i++){
	        	abnomalStr += "<tr>"
						+"<td></td>"
						+"<td></td>"
						+"<td></td>"
						+"<td></td>"
						+"<td></td>"
						+"<td></td>"
						+"<td></td>"
						+"<td></td>"
						+"<td></td>"
						+"<td></td>"
						+"<td></td>"
						+"</tr>";
	        }
	        model.put("abnomalList",abnomalStr);
	        model.put("EntList",entStr);
	        model.put("rank",12);
	        model.put("vehicleCount",123);
	        model.put("vehicleNetCount",111);
	        model.put("enterpriseName","亿程");
	        model.put("enterpriseCount", 30);
	        model.put("dealRate","85%");
	        model.put("week", DateUtil.getDayOfWeek(new Date())-1);
            MailSendUtil.sendHtmlMail(info,model);
            
            //发送文本
            String content = "<div>你不在学校吗？</div><br/><hr/><div>记得28号来学校</div>";
            info.setContent(content);
     //       MailSendUtil.sendTextMail(info);
            
        } catch (Exception e) {
            System.out.print("邮件发送失败！");
            e.printStackTrace();
        }
	}
}